const timeout = 10 * 1000; //超时时间
import {
	localStorage
} from '../store/mp-storage/mp-storage/index.js'

/**
 * 显示提示
 * @param {Object} message
 */
function showToast(message) {
	uni.showToast({
		title: message,
		duration: 1500,
		icon: 'none',
	});
}


var rh = {
	url: '',
	data: {},
	header: {
		'Content-Type': 'application/x-www-form-urlencoded'
	},
	method: 'get',
	dataType: 'json',
	success: function(result, status) {},
	fail: function() {
		showToast("网络飞走了~")
	},
	error: function(data) {
		showToast(data.status ? '访问异常: ' + data.status.msg : '网络有点问题哦，请稍后再试~')
	},
	complete: function() {}
}

function genUuid() {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";
	var uuid = s.join("");
	return uuid;
}

function fetchImgUploadToken(imgUrl, callback) {
	// 获取图片上传的token
	let cacheToken = localStorage.getItem('ys-imgToken');
	let now = new Date().getTime() / 1000;
	console.log('查询图片的token', cacheToken, now);
	if (cacheToken) {
		cacheToken = JSON.parse(cacheToken);
		if (cacheToken.expireAt > now + 300) {
			if (callback) {
				callback(cacheToken);
			}
			return cacheToken;
		}
	}

	let _this = this;
	this.req({
		url: imgUrl,
		method: "get",
		data: {},
		dataType: 'json',
		success: function(result, status) {
			console.log('查询imgToken 获取token:', result);
			localStorage.setItem('ys-imgToken', JSON.stringify(result));
			if (callback) {
				// 回传token，做业务逻辑执行
				callback(result);
			}
		},
	});
	return "";
}

function saveToken(token) {
	// 保存登录凭证
	this.removeToken()
	localStorage.setItem('ys-token', token);
	console.log('保存token: -->', token, '缓存中-->', getLoginToken());
}

function removeToken() {
	// 删除登录凭证
	localStorage.removeItem('ys-token');
	rh.header['ys-token'] = null;
	console.log('删除token: ', getLoginToken());
}

function getLoginToken() {
	return localStorage.getItem('ys-token');
}

function req(requestHandler) {
	var data = requestHandler.data;
	var url = requestHandler.url;
	var method = requestHandler.method;

	let headers = requestHandler.header || {'Content-Type': 'application/x-www-form-urlencoded'};
	if (!headers['d-uuid']) {
		let uuid = localStorage.getItem('d-uuid');
		if (!uuid) {
			uuid = genUuid();
			console.log('生成uuid: ', uuid);
			localStorage.setItem('d-uuid', uuid);
		}
		headers['d-uuid'] = uuid;
	}
	console.log('写token之前请求头:', url, data, headers);
	if (!headers['ys-token']) {
		let token = getLoginToken();
		console.log('缓存中的token:', token);
		if (token) {
			headers['ys-token'] = token;
		}
	}
	console.log('请求头:', url, headers);

	let dataType = requestHandler.dataType || rh.dataType

	uni.request({
		url: url,
		data: data,
		dataType: dataType,
		header: headers,
		method: method || rh.method,
		success: function(res) {
			if (dataType != 'json') {
				// 非json返回时
				requestHandler.success(res)
				return;
			}
			let {
				result,
				status
			} = res.data;
			if (status && status.code == 0) {
				requestHandler.success(result, status)
			} else if (status && status.code == 100_403_003) {
				// 未登录
				showToast("请登录之后再来操作吧")
				// 去登录页面
				// #ifdef MP-WEIXIN
				uni.navigateTo({
					'url': "/pages/user/login/login"
				})
				// #endif
				// #ifndef MP-WEIXIN
				uni.navigateTo({
					'url': "/pages/public/login"
				})
				// #endif
			} else if (requestHandler.error) {
				requestHandler.error(res.data);
			} else {
				rh.error(res.data);
			}
		},
		fail: function() {
			if (requestHandler.fail) {
				requestHandler.fail();
			} else {
				rh.fail();
			}
		},
		complete: function() {
			if (requestHandler.complete) {
				requestHandler.complete();
			} else {
				rh.complete();
			}
		}
	})
}


module.exports = {
	req: req,
	saveToken: saveToken,
	removeToken: removeToken,
	fetchImgUploadToken: fetchImgUploadToken,
}